package com.jzy.bxb.app.scripts.http.user;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;

import com.jzy.bxb.app.manager.OrderManager;
import com.jzy.bxb.app.manager.RedisManager;
import com.jzy.bxb.app.server.AuthHttpHandler;
import com.jzy.bxb.core.handler.HandlerEntity;
import com.jzy.bxb.core.handler.HttpHandler;
import com.jzy.bxb.core.util.StringUtil;
import com.jzy.bxb.model.constant.AppConstant;
import com.jzy.bxb.model.constant.RedisKey;
import com.jzy.bxb.model.constant.UserType;
import com.jzy.bxb.model.mongo.dao.ConfigCityDao;
import com.jzy.bxb.model.mongo.dao.UserDao;
import com.jzy.bxb.model.mongo.entity.Address;
import com.jzy.bxb.model.mongo.entity.User;
import com.jzy.bxb.model.mongo.entity.config.ConfigCity;
import com.jzy.bxb.model.mongo.entity.config.ConfigCounty;
import com.jzy.bxb.model.util.UMPushUtil;

import redis.clients.jedis.Jedis;

/**
 * 设置帮手
 * <p>
 * http://127.0.0.1:8680/user/assistant/address?sid=c6241261-1bff-461f-81a1-7a0bc5470319&fullAddr=chengdu&community=yongle&unitNo=1&&houseNo=101<br>
 * 
 * <li>type 0 添加地址 1删除地址，只需要传小区</li>
 * <li>password 管理员密码 c6241261-1bff-461f-81a1-7a0bc5470319</li>
 * <li>userId 帮手用户ID
 * <li>
 * <li>city 城市</li>
 * <li>county 区县</li>
 * <li>community 小区</li>
 * 
 * </p>
 * 
 * @author JiangZhiYong
 * @date 2017-07-13 QQ:359135103
 */
@HandlerEntity(path = "/user/assistant/address")
public class AssistantAddressHandler extends HttpHandler {

	@Override
	public void run() {
		String password = getString("password");
		if (password == null || !password.equals(AppConstant.MANAGE_AUTH)) {
			sendError("密码错误");
			return;
		}
		long userId = getLong("userId");
		if (userId < 1) {
			sendError("请选择用户");
			return;
		}
		User assistant = UserDao.getById(userId);
		if (assistant == null) {
			sendError("用户未找到");
			return;
		}

		int type = getInt("type");
		if (type == 0) {
			addAddress(assistant);
		} else if (type == 1) {
			removeAddress(assistant);
		}
	}

	public void removeAddress(User assistant) {
		String community = getString("community");
		if (StringUtil.isEmpty(community)) {
			sendError("请选择小区");
			return;
		}
		if (assistant.getAssistantAddress() == null) {
			return;
		}
		Iterator<Address> iterator = assistant.getAssistantAddress().iterator();
		while (iterator.hasNext()) {
			Address address = iterator.next();
			if (address.getCommunity().equals(community)) {
				iterator.remove();
				String redisField = OrderManager.getInstance().getRedisAddressStr(address);
				Jedis client = RedisManager.getInstance().getClient();
				client.hdel(RedisKey.AreaAssistantMap.getKey(), redisField);
				client.close();
				UMPushUtil.sendAndroidBroadcast("移除服务区", "移除服务区", String.format("小区：%s移除", community), null);
				UMPushUtil.sendIOSBroadcast( String.format("小区：%s移除", community), null);
				break;
			}
		}
		if (assistant.getAssistantAddress().size() < 1) {
			assistant.setUserType(UserType.EMPLOYER.getType());
		}
		UserDao.saveUser(assistant);
		sendMsg(String.format("小区：%s已取消服务", community));

	}

	/**
	 * 添加地址
	 * 
	 * @param assistant
	 * @author JiangZhiYong
	 * @date 2017-07-13 QQ:359135103
	 */
	private void addAddress(User assistant) {
		String city = getString("city");
		String county = getString("county");
		String community = getString("community");

		if (StringUtil.isEmpty(city) || StringUtil.isEmpty(county) || StringUtil.isEmpty(community)) {
			sendError("请设置请求参数");
			return;
		}

		if (assistant.getUserType() == UserType.EMPLOYER.getType()) {
			assistant.setUserType(UserType.ASSISTANT.getType());
		}
		if (assistant.getAssistantAddress() == null) {
			assistant.setAssistantAddress(new ArrayList<>());
		}

		Address address = new Address();
		address.setCity(city);
		address.setCounty(county);
		address.setCommunity(community);
		
		//设置有哪些服务器城市
		ConfigCity configCity = ConfigCityDao.getConfigCity(city);
		if(configCity==null){
			configCity=new ConfigCity();
			configCity.setName(city);
			configCity.getCounty().add(new ConfigCounty(county));
			Optional<ConfigCounty> findAny = configCity.getCounty().stream().filter(c->c.getName().equals(county)).findAny();
			if(findAny.isPresent()){
				findAny.get().getCommunity().add(community);
			}
			ConfigCityDao.saveConfigCity(configCity);
		}
		Optional<ConfigCounty> findAny = configCity.getCounty().stream().filter(c->c.getName().equals(county)).findAny();
		if(!findAny.isPresent()){
			ConfigCounty configCounty=new ConfigCounty(county);
			configCounty.getCommunity().add(community);
			configCity.getCounty().add(configCounty);
		}else{
			if(!findAny.get().getCommunity().stream().anyMatch(c->c.equals(community))){
				findAny.get().getCommunity().add(community);
			}
		}
		
		String redisField = OrderManager.getInstance().getRedisAddressStr(address);
		Jedis client = RedisManager.getInstance().getClient();
		client.hset(RedisKey.AreaAssistantMap.getKey(), redisField, String.valueOf(assistant.getId()));
		client.close();
		UMPushUtil.sendAndroidBroadcast("添加服务区", "添加服务区", String.format("小区：%s添加服务区", community), null);
		UMPushUtil.sendIOSBroadcast(String.format("小区：%s添加服务区", community), null);

		assistant.getAssistantAddress().add(address);
		UserDao.saveUser(assistant);
		sendMsg(assistant.getAssistantAddress());
	}

}
